package ali.action;


import ali.compass.Compass;
import ali.entities.Something;
import ali.pathresolver.SinglePathResolver;
import ali.point.Point;
import ali.timer.Timer;
import ali.timer.TimerListener;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * User: aliolci
 * Date: 20/05/11
 * Time: 00:29
 */
public class SomethingMoving implements TimerListener{
    private List<SomethingMovingListener> movingListenerSequence = new ArrayList<SomethingMovingListener>();
    private Something somethingAffected;
    private Speed speed;
    private Timer timer= new Timer(this);
    private SinglePathResolver pathResolver;

    public SomethingMoving(Something somethingIsGonnaAffected){
        this.somethingAffected=somethingIsGonnaAffected;
    }

    public void go(Speed speed, Point destination){
        this.speed=speed;
        pathResolver = new SinglePathResolver(somethingAffected.getLocation(),destination,speed);
        timer.start();
    }

    public void tick() {
        if(pathResolver.hasNext()){
        onMove(pathResolver.getNextLocation());
        } else {
            timer.stop();
            stop();
        }
    }

    public void start() {
        onStart();
    }

    public void stop(){
        onStop();
    }


    public Compass getCompass(){
        return pathResolver.getCompass();
    }
    public Speed getSpeed(){
        return this.speed;
    }
    private void onMove(Point point) {
        Iterator<SomethingMovingListener> iterator = movingListenerSequence.iterator();
        while(iterator.hasNext()){
            iterator.next().onMove(point);
        }
    }

    private void onStop() {
        Iterator<SomethingMovingListener> iterator = movingListenerSequence.iterator();
        while(iterator.hasNext()){
            iterator.next().onStop();
        }
    }

    private void onStart() {
        Iterator<SomethingMovingListener> iterator = movingListenerSequence.iterator();
        while(iterator.hasNext()){
            iterator.next().onStart();
        }
    }
    public void addSomethingMovingListener(SomethingMovingListener listener){
        this.movingListenerSequence.add(listener);
    }
    public void removeSomethingMovingListener(SomethingMovingListener listener){
        this.movingListenerSequence.remove(listener);
    }
}

